﻿using RearLivestock.Common.DBContexts;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Infrastructure.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RearLivestock.Common.Infrastructure.Repositories
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        /// <summary>
        /// EF上下文
        /// </summary>
        private readonly EFDBContext db;
        public EFDBContext DB { get { return db; } }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db">EF上下文</param>
        public BaseRepository(EFDBContext db)
        {
            this.db = db;
        }

        /// <summary>
        /// 返回所有数据
        /// </summary>
        /// <returns>所有数据</returns>
        public async Task<IQueryable<T>> GetAll()
        {
            var res = db.Set<T>();
            return res;
        }

        /// <summary>
        /// 没有异步获取所有数据
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> Query()
        {
            return db.Set<T>().AsQueryable();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>改变的行数</returns>
        public async Task<int> Add(T entity)
        {
            db.Set<T>().Add(entity);
            return db.SaveChanges();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>改变的行数</returns>
        public async Task<int> Update(T entity)
        {
            db.Set<T>().Update(entity);
            return db.SaveChanges();
        }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="entities">实体</param>
        /// <returns></returns>
        public int AddRange(List<T> entities)
        {
            db.Set<T>().AddRange(entities);
            return db.SaveChanges();
        }

        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="entities">实体</param>
        /// <returns></returns>
        public int UpdRange(List<T> entities)
        {
            db.Set<T>().UpdateRange(entities);
            return db.SaveChanges();
        }

        public int AddRange(IEnumerable<object> ablactations)
        {
            throw new NotImplementedException();
        }

        public int AddRange(object ablactations)
        {
            throw new NotImplementedException();
        }
    }
}
